/*
 * @Author: 自迩
 * @Date: 2022-02-04 11:41:30
 * @LastEditTime: 2022-02-08 12:00:39
 * @LastEditors: your name
 * @Description:
 * @FilePath: \silence-reader\src\App.js
 */
import "./App.css";
import { Route, Routes } from "react-router-dom";
import Book from "./pages/book";
import Bookshelf from "./pages/bookshelf";
import React, { useReducer } from "react";
import { Button } from "antd";
import './App.css';

export const BookListContext = React.createContext();

const reducer = (state, action) => {
  switch (action.type) {
    case "addBooks":
      return handleAddBooks(state, action.value);
    case "deleteBooks":
      return handleDeleteBooks(state, action.value);
    default:
      return state;
  }
};
const bookListInitialState = [];
function handleAddBooks(state, fileLists) {
  let currentTime = new Date().getTime();
  //格式化书
  let newUploadList = fileLists.map((value) => {
    return {
      bookName: value.fileName,
      author: "佚名",
      createTime: currentTime,
      updateTime: undefined,
      file: value.file,
    };
  });

  let shouldAddBookList = newUploadList.filter((newUploadBook) => {
    return (
      state.findIndex((tmp) => {
        return tmp.bookName === newUploadBook.bookName;
      }) < 0
    );
  });
  return [...state, ...shouldAddBookList];
}
function handleDeleteBooks(state, bookName) {
  let afterDeleteBookList = state.filter((oldBook) => {
    return oldBook.bookName !== bookName;
  });
  return [...afterDeleteBookList];
}

function App() {
  const [bookList, dispatch] = useReducer(reducer, bookListInitialState);
  return (
    <div className="App">

      <BookListContext.Provider
        value={{
          bookListContext: bookList,
          bookListDispatch: dispatch,
        }}
      >

        <Routes>
          <Route path="/book/:bookName" element={<Book />}></Route>
          <Route path="/bookshelf" element={<Bookshelf />}></Route>
          <Route path="/" element={<Bookshelf />}></Route>

          {/* <Route path="/" element={<Book />}></Route> */}
        </Routes>
      </BookListContext.Provider>
    </div>
  );
  <div className="App">
    <Button type="primary">Button</Button>
  </div>
}

export default App;
